package org.kmfdm.horrorscope.tapestry.pages.user;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.kmfdm.horrorscope.core.spring.ApplicationContextProviderSingleton;
import org.kmfdm.horrorscope.enums.ChartType;
import org.kmfdm.horrorscope.enums.Gender;
import org.kmfdm.horrorscope.metamodel.Chart;
import org.kmfdm.horrorscope.metamodel.Customer;
import org.kmfdm.horrorscope.metamodel.User;
import org.kmfdm.horrorscope.service.CreateChart;
import org.apache.tapestry5.util.EnumSelectModel;

import org.kmfdm.horrorscope.tapestry.pages.Info;
import org.springframework.context.ApplicationContext;

public class AddChart {
	
	@SessionState
	private User user;
	
	private Chart chart;
	@Inject
	private CreateChart createChart;
	@InjectPage
	private Info info;
	
	
	
	@Component(id="chartCreation")
	private Form chartCreation;
	
	
	private ApplicationContext applicationContext(){
		return new ApplicationContextProviderSingleton().getContext();
	}
	private Chart makeChart(){
		return (Chart) applicationContext().getBean(Chart.class.getName());
	}
	public void setChart(Chart chart) {
		this.chart = chart;
	}
	public Chart getChart() {
		if(chart==null){
			chart=makeChart();
		}
		return chart;
	}
	@OnEvent(component="chartCreation")
	public Object onSuccess(){
		chart.setOwner((Customer)user);
		createChart.createChart(chart);
		
		info.setMessage("Chart input successful!");
		return info;
		
	}
	@Inject
	private Messages messages;
	
	public SelectModel getGenderType() {
		return new EnumSelectModel(Gender.class, messages);
	}
	
	public SelectModel getChartType() {
		return new EnumSelectModel(ChartType.class, messages);
	}
}